/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package modules.estoque.util;

import java.awt.image.BufferedImage;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.imageio.ImageReader;
import javax.imageio.stream.ImageInputStream;
import javax.swing.ImageIcon;
import javax.swing.JFormattedTextField;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import javax.swing.text.MaskFormatter;
import javax.swing.text.html.StyleSheet.BoxPainter;
import modules.estoque.validation.Error;

/**
 *
 * @author Clezio
 */
public class Funcoes {

    public static void registrarLogErro(Exception err) {
        String sMensagem = "";
        if (err != null) {
            sMensagem += "###################" + new Date() + "###################\r\n";
            sMensagem += "Locale=>" + err.getLocalizedMessage();
            for (int i = 0; err.getStackTrace().length > i; i++) {
                if (i == 0) {
                    sMensagem += "\r\nTrace:";
                }
                sMensagem += "\r\n" + err.getStackTrace()[i].toString();
            }
            sMensagem += "\r\n############################## FIM ####################################\r\n\r\n\r\n\r\n";
        }
        if (!sMensagem.equals("")) {
            salvarArquivo("LogWms.txt", sMensagem, true);
        }
    }

    public static void salvarArquivo(String arquivo, String mensagem, boolean sContinue) {
        try {
            BufferedWriter out = null;
            if (new File(arquivo).exists()) {
                out = new BufferedWriter(new FileWriter(arquivo, true));
            } else {
                out = new BufferedWriter(new FileWriter(arquivo));
            }
            out.write(mensagem); // "" = quebra de linha no Windows
            out.close();
        } catch (IOException erro) {
            BoxPanel.showMessageDialog(null, "Não foi possível escrever no arquivo especificado.");
        }
    }

    public static boolean validaCnpj(String cnpj) {
        int soma = 0, aux, dig;
        cnpj = cnpj.replace(".", "").replace("-", "");
        String cnpj_calc = cnpj.substring(0, 12);

        if (cnpj.length() != 14) {
            return false;
        }

        char[] chr_cnpj = cnpj.toCharArray();

        /* Primeira parte */
        for (int i = 0; i < 4; i++) {
            if (chr_cnpj[i] - 48 >= 0 && chr_cnpj[i] - 48 <= 9) {
                soma += (chr_cnpj[i] - 48) * (6 - (i + 1));
            }
        }
        for (int i = 0; i < 8; i++) {
            if (chr_cnpj[i + 4] - 48 >= 0 && chr_cnpj[i + 4] - 48 <= 9) {
                soma += (chr_cnpj[i + 4] - 48) * (10 - (i + 1));
            }
        }
        dig = 11 - (soma % 11);

        cnpj_calc += (dig == 10 || dig == 11)
                ? "0" : Integer.toString(dig);

        /* Segunda parte */
        soma = 0;
        for (int i = 0; i < 5; i++) {
            if (chr_cnpj[i] - 48 >= 0 && chr_cnpj[i] - 48 <= 9) {
                soma += (chr_cnpj[i] - 48) * (7 - (i + 1));
            }
        }
        for (int i = 0; i < 8; i++) {
            if (chr_cnpj[i + 5] - 48 >= 0 && chr_cnpj[i + 5] - 48 <= 9) {
                soma += (chr_cnpj[i + 5] - 48) * (10 - (i + 1));
            }
        }
        dig = 11 - (soma % 11);
        cnpj_calc += (dig == 10 || dig == 11)
                ? "0" : Integer.toString(dig);
        return cnpj.equals(cnpj_calc);
    }

    public static String getListErros(List<Error> erros) {
        String lista = "";
        for (int i = 0; i < erros.size(); i++) {
            if (i > 0) {
                lista += "\r\n";
            }
            lista += "- " + erros.get(i);
        }
        return lista;
    }

    public static String dateToString(Date date) {
        SimpleDateFormat dateformatMMDDYYYY = new SimpleDateFormat("dd/MM/yyyy");
        return new StringBuilder(dateformatMMDDYYYY.format(date)).toString();
    }

    public static Date stringToDate(String dateString) throws ParseException {
        DateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
        return (Date) formatter.parse(dateString);
    }

    public static DecimalFormat factoryDecimalFormat(String format) {
        return new java.text.DecimalFormat(format);
    }

    public static ImageIcon showIcon(String path, Integer key) throws IOException {
        File file = new File(path);
        ImageInputStream in = ImageIO.createImageInputStream(new FileInputStream(file));
        Iterator it = ImageIO.getImageReaders(in);
        while (it.hasNext()) {
            try {
                ImageReader r = (ImageReader) it.next();
                r.setInput(in);
                if (key == null) {
                    BufferedImage im = r.read(0);
                    return new ImageIcon(im);
                } else {
                    int nr = r.getNumImages(true);
                    for (int i = 0; i < nr; i++) {
                        BufferedImage im = r.read(i);
                        if(i == key){
                            return new ImageIcon(im);
                        }
                    }
                }
                //reading the image was successfull, so break the loop
                break;
            } catch (Exception ex) {
//                in = ImageIO.createImageInputStream(new FileInputStream(file));
                return null;
            }
        }
        return null;
    }

    public static void formataCampoData(JTextField tfData) {
        try {
            tfData = new JFormattedTextField(new MaskFormatter("##/##/####"));
        } catch (ParseException ex) {
            Logger.getLogger(Funcoes.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}
